<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Mybatis-Plus笔记 | IU的小迷弟</title><meta name="keywords" content="Mybatis-Plus"><meta name="author" content="IU的小迷弟"><meta name="copyright" content="IU的小迷弟"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Mybatis-Plus 此版本为Mybatis-Plus(3.0.5)+Spring-Boot(2.6.3)；新版本为Mybatis-Plus(3.0.5)，SpringBoot不变  MyBatis-Plus (opens new window)（简称 MP）是一个 MyBatis (opens new window)的增强工具，在 MyBatis 的基础上只做增强不做改变，为简化开发、提高效">
<meta property="og:type" content="article">
<meta property="og:title" content="Mybatis-Plus笔记">
<meta property="og:url" content="https://www.loveiu.top/20220622/mybatiis_plus/">
<meta property="og:site_name" content="IU的小迷弟">
<meta property="og:description" content="Mybatis-Plus 此版本为Mybatis-Plus(3.0.5)+Spring-Boot(2.6.3)；新版本为Mybatis-Plus(3.0.5)，SpringBoot不变  MyBatis-Plus (opens new window)（简称 MP）是一个 MyBatis (opens new window)的增强工具，在 MyBatis 的基础上只做增强不做改变，为简化开发、提高效">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://www.loveiu.top/img/79.jpg">
<meta property="article:published_time" content="2022-06-22T06:29:00.000Z">
<meta property="article:modified_time" content="2022-06-22T06:50:14.332Z">
<meta property="article:author" content="IU的小迷弟">
<meta property="article:tag" content="-笔记">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://www.loveiu.top/img/79.jpg"><link rel="shortcut icon" href="/img/1609046896790.jpg"><link rel="canonical" href="https://www.loveiu.top/20220622/mybatiis_plus/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="baidu-site-verification" content="ccded20f230f88c302adfd1c809bdbaa"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://unpkg.com/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://unpkg.com/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?ccded20f230f88c302adfd1c809bdbaa";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"簡","msgToSimplifiedChinese":"簡"},
  noticeOutdate: {"limitDay":365,"position":"top","messagePrev":"It has been","messageNext":"days since the last update, the content of the article may be outdated."},
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":200},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: IU的小迷弟","link":"链接: ","source":"来源: IU的小迷弟","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"top-right"},
  source: {
    jQuery: 'https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js',
    justifiedGallery: {
      js: 'https://unpkg.com/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://unpkg.com/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://unpkg.com/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://unpkg.com/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-06-22 14:50:14'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    })(window)</script><meta name="viewport"><meta name="referrer" content="origin-when-cross-origin"><link rel="stylesheet" href="https://at.alicdn.com/t/font_2492531_8fw76pwhl1n.css" /><link rel="stylesheet" href="/css/iconfont/iconfont.css"/><link rel="stylesheet" href="/css/iconfont2/iconfont.css"/><script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script><link href="https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"><script src="/js/sweetalert_two.js"></script><script type="text/javascript" src ="/js/welcome.js" ></script><link  rel="stylesheet" href="/css/sweetalert.css"></link><div id="web_bgs"></div><meta name="generator" content="Hexo 5.4.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" data-lazy-src="/img/1609046896790.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">13</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">8</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">6</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw iconfont icon-house"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fa-fw iconfont icon-tongxunlu"></i><span> 文章</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/tags/"><i class="fa-fw iconfont icon-chuangzuo-tianchong"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw iconfont icon-nightstand"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw iconfont icon-telephone"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/artitalk/"><i class="fa-fw iconfont icon-telephone"></i><span> 说说</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fa-fw iconfont icon-cha"></i><span> 生活</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw iconfont icon-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/imgs/"><i class="fa-fw iconfont icon-xiangce"></i><span> 图库</span></a></li><li><a class="site-page child" href="/demo/dm/%E5%8A%A8%E6%BC%AB.html"><i class="fa-fw iconfont icon-heart"></i><span> 动漫</span></a></li><li><a class="site-page child" href="/wqj/"><i class="fa-fw iconfont icon-shengdantubiao-06"></i><span> 圣诞树</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fa-fw fas fa-list"></i><span> 其他链接</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" target="_blank" rel="noopener external nofollow noreferrer" href="https://xiaozhidage.gitee.io"><i class="fa-fw iconfont icon-gitee-copy"></i><span> Gitee Page</span></a></li><li><a class="site-page child" target="_blank" rel="noopener external nofollow noreferrer" href="https://pzloveyou.github.io"><i class="fa-fw iconfont icon-GitHub1-copy"></i><span> Github Page</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw iconfont icon-sun"></i><span> 关于作者</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/img/79.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">IU的小迷弟</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw iconfont icon-house"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fa-fw iconfont icon-tongxunlu"></i><span> 文章</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/tags/"><i class="fa-fw iconfont icon-chuangzuo-tianchong"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw iconfont icon-nightstand"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw iconfont icon-telephone"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/artitalk/"><i class="fa-fw iconfont icon-telephone"></i><span> 说说</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fa-fw iconfont icon-cha"></i><span> 生活</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw iconfont icon-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/imgs/"><i class="fa-fw iconfont icon-xiangce"></i><span> 图库</span></a></li><li><a class="site-page child" href="/demo/dm/%E5%8A%A8%E6%BC%AB.html"><i class="fa-fw iconfont icon-heart"></i><span> 动漫</span></a></li><li><a class="site-page child" href="/wqj/"><i class="fa-fw iconfont icon-shengdantubiao-06"></i><span> 圣诞树</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fa-fw fas fa-list"></i><span> 其他链接</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" target="_blank" rel="noopener external nofollow noreferrer" href="https://xiaozhidage.gitee.io"><i class="fa-fw iconfont icon-gitee-copy"></i><span> Gitee Page</span></a></li><li><a class="site-page child" target="_blank" rel="noopener external nofollow noreferrer" href="https://pzloveyou.github.io"><i class="fa-fw iconfont icon-GitHub1-copy"></i><span> Github Page</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw iconfont icon-sun"></i><span> 关于作者</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Mybatis-Plus笔记</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-06-22T06:29:00.000Z" title="发表于 2022-06-22 14:29:00">2022-06-22</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-06-22T06:50:14.332Z" title="更新于 2022-06-22 14:50:14">2022-06-22</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E8%B8%A9%E5%9D%91/">踩坑</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">3.9k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>18分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Mybatis-Plus笔记"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="Mybatis-Plus"><a href="#Mybatis-Plus" class="headerlink" title="Mybatis-Plus"></a>Mybatis-Plus</h1><blockquote>
<p><strong>此版本为Mybatis-Plus(3.0.5)+Spring-Boot(2.6.3)<strong>；</strong>新版本为Mybatis-Plus(3.0.5)，SpringBoot不变</strong></p>
</blockquote>
<p><a target="_blank" rel="noopener external nofollow noreferrer" href="https://github.com/baomidou/mybatis-plus">MyBatis-Plus (opens new window)</a>（简称 MP）是一个 <a target="_blank" rel="noopener external nofollow noreferrer" href="https://www.mybatis.org/mybatis-3/">MyBatis (opens new window)</a>的增强工具，在 MyBatis 的基础上只做增强不做改变，为简化开发、提高效率而生。</p>
<ul>
<li><strong>无侵入</strong>：只做增强不做改变，引入它不会对现有工程产生影响，如丝般顺滑</li>
<li><strong>损耗小</strong>：启动即会自动注入基本 CURD，性能基本无损耗，直接面向对象操作</li>
<li><strong>强大的 CRUD 操作</strong>：内置通用 Mapper、通用 Service，仅仅通过少量配置即可实现单表大部分 CRUD 操作，更有强大的条件构造器，满足各类使用需求</li>
<li><strong>支持 Lambda 形式调用</strong>：通过 Lambda 表达式，方便的编写各类查询条件，无需再担心字段写错</li>
<li><strong>支持主键自动生成</strong>：支持多达 4 种主键策略（内含分布式唯一 ID 生成器 - Sequence），可自由配置，完美解决主键问题</li>
<li><strong>支持 ActiveRecord 模式</strong>：支持 ActiveRecord 形式调用，实体类只需继承 Model 类即可进行强大的 CRUD 操作</li>
<li><strong>支持自定义全局通用操作</strong>：支持全局通用方法注入（ Write once, use anywhere ）</li>
<li><strong>内置代码生成器</strong>：采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码，支持模板引擎，更有超多自定义配置等您来使用</li>
<li><strong>内置分页插件</strong>：基于 MyBatis 物理分页，开发者无需关心具体操作，配置好插件之后，写分页等同于普通 List 查询</li>
<li><strong>分页插件支持多种数据库</strong>：支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库</li>
<li><strong>内置性能分析插件</strong>：可输出 SQL 语句以及其执行时间，建议开发测试时启用该功能，能快速揪出慢查询</li>
<li><strong>内置全局拦截插件</strong>：提供全表 delete 、 update 操作智能分析阻断，也可自定义拦截规则，预防误操作</li>
</ul>
<h1 id="快速开始"><a href="#快速开始" class="headerlink" title="快速开始"></a>快速开始</h1><p>1.创建数据库mybatis-plus</p>
<p>2.新建User表</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">DROP</span> <span class="keyword">TABLE</span> IF <span class="keyword">EXISTS</span> <span class="keyword">user</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> <span class="keyword">user</span></span><br><span class="line">(</span><br><span class="line">	id <span class="type">BIGINT</span>(<span class="number">20</span>) <span class="keyword">NOT</span> <span class="keyword">NULL</span> COMMENT <span class="string">&#x27;主键ID&#x27;</span>,</span><br><span class="line">	name <span class="type">VARCHAR</span>(<span class="number">30</span>) <span class="keyword">NULL</span> <span class="keyword">DEFAULT</span> <span class="keyword">NULL</span> COMMENT <span class="string">&#x27;姓名&#x27;</span>,</span><br><span class="line">	age <span class="type">INT</span>(<span class="number">11</span>) <span class="keyword">NULL</span> <span class="keyword">DEFAULT</span> <span class="keyword">NULL</span> COMMENT <span class="string">&#x27;年龄&#x27;</span>,</span><br><span class="line">	email <span class="type">VARCHAR</span>(<span class="number">50</span>) <span class="keyword">NULL</span> <span class="keyword">DEFAULT</span> <span class="keyword">NULL</span> COMMENT <span class="string">&#x27;邮箱&#x27;</span>,</span><br><span class="line">	<span class="keyword">PRIMARY</span> KEY (id)</span><br><span class="line">);</span><br><span class="line"><span class="keyword">DELETE</span> <span class="keyword">FROM</span> <span class="keyword">user</span>;</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> <span class="keyword">user</span> (id, name, age, email) <span class="keyword">VALUES</span></span><br><span class="line">(<span class="number">1</span>, <span class="string">&#x27;Jone&#x27;</span>, <span class="number">18</span>, <span class="string">&#x27;test1@baomidou.com&#x27;</span>),</span><br><span class="line">(<span class="number">2</span>, <span class="string">&#x27;Jack&#x27;</span>, <span class="number">20</span>, <span class="string">&#x27;test2@baomidou.com&#x27;</span>),</span><br><span class="line">(<span class="number">3</span>, <span class="string">&#x27;Tom&#x27;</span>, <span class="number">28</span>, <span class="string">&#x27;test3@baomidou.com&#x27;</span>),</span><br><span class="line">(<span class="number">4</span>, <span class="string">&#x27;Sandy&#x27;</span>, <span class="number">21</span>, <span class="string">&#x27;test4@baomidou.com&#x27;</span>),</span><br><span class="line">(<span class="number">5</span>, <span class="string">&#x27;Billie&#x27;</span>, <span class="number">24</span>, <span class="string">&#x27;test5@baomidou.com&#x27;</span>);</span><br></pre></td></tr></table></figure>

<p>3.编写项目。初始化项目，springboot</p>
<p>4.配置数据库源</p>
<p>5.pom.xml</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line">	<span class="tag">&lt;<span class="name">properties</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">java.version</span>&gt;</span>1.8<span class="tag">&lt;/<span class="name">java.version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">properties</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-web<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>mysql<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mysql-connector-java<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">scope</span>&gt;</span>runtime<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!--     mybatis-plus核心--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.baomidou<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mybatis-plus-boot-starter<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.4.1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!--        代码生成--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.baomidou<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mybatis-plus-generator<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.4.1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!--        代码生成模板--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.apache.velocity<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>velocity-engine-core<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.3<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!--        sql打印分析--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>p6spy<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>p6spy<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.9.1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.projectlombok<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>lombok<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">optional</span>&gt;</span>true<span class="tag">&lt;/<span class="name">optional</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-test<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">scope</span>&gt;</span>test<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br></pre></td></tr></table></figure>



<p>…….省略</p>
<h1 id="配置日志"><a href="#配置日志" class="headerlink" title="配置日志"></a>配置日志</h1><p>1.配置文件添加</p>
<figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl</span></span><br></pre></td></tr></table></figure>



<h1 id="CRUD扩展"><a href="#CRUD扩展" class="headerlink" title="CRUD扩展"></a>CRUD扩展</h1><p>简单操作不用再写sql，直接使用mybatis-plus封装的方法即可完成简单的crud操作。</p>
<p>Mapper继承BaseMapp<T>;T代表泛型</p>
<h2 id="CRUD测试"><a href="#CRUD测试" class="headerlink" title="CRUD测试"></a>CRUD测试</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Autowired</span></span><br><span class="line">   <span class="keyword">private</span> UserMapper userMapper;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line">   <span class="function"><span class="keyword">void</span> <span class="title">contextLoads</span><span class="params">()</span> </span>&#123;</span><br><span class="line">       <span class="comment">//参数Wrapper，条件构造器</span></span><br><span class="line">       <span class="comment">//查询全部用户</span></span><br><span class="line">       List&lt;User&gt; users = userMapper.selectList(<span class="keyword">null</span>);</span><br><span class="line">       users.forEach(System.out::println);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">//测试插入</span></span><br><span class="line">   <span class="meta">@Test</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testInsert</span><span class="params">()</span></span>&#123;</span><br><span class="line">       User user=<span class="keyword">new</span> User();</span><br><span class="line">       user.setName(<span class="string">&quot;pzy&quot;</span>);</span><br><span class="line">       user.setAge(<span class="number">1</span>);</span><br><span class="line">       user.setEmail(<span class="string">&quot;2831053223@qq.com&quot;</span>);</span><br><span class="line">       <span class="keyword">int</span> result=userMapper.insert(user);  <span class="comment">//自动生成id</span></span><br><span class="line">       System.out.println(result);</span><br><span class="line">   &#125;</span><br><span class="line">  <span class="comment">//测试更新</span></span><br><span class="line">   <span class="meta">@Test</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testUpdate</span><span class="params">()</span></span>&#123;</span><br><span class="line">       User user=<span class="keyword">new</span> User();</span><br><span class="line">       user.setId(<span class="number">5L</span>);</span><br><span class="line">       user.setName(<span class="string">&quot;pzy&quot;</span>);</span><br><span class="line">       user.setAge(<span class="number">1</span>);</span><br><span class="line">       user.setEmail(<span class="string">&quot;2831053223@qq.com&quot;</span>);</span><br><span class="line">       <span class="keyword">int</span> result=userMapper.updateById(user);</span><br><span class="line">       System.out.println(result);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="comment">//测试删除</span></span><br><span class="line">   <span class="meta">@Test</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testDelete</span><span class="params">()</span></span>&#123;</span><br><span class="line">       User user=<span class="keyword">new</span> User();</span><br><span class="line">       user.setId(<span class="number">5L</span>);</span><br><span class="line">       <span class="keyword">int</span> result=userMapper.deleteById(user);</span><br><span class="line">       System.out.println(result);</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>



<h2 id="主键生成策略"><a href="#主键生成策略" class="headerlink" title="主键生成策略"></a>主键生成策略</h2><p>​    <strong>雪花算法</strong>:</p>
<ul>
<li><p>​    snowflake ………</p>
</li>
<li><p>​    实体类 @TableId(type = IdType.ID_WORKER) :全局唯一ID;   @TableId(type = IdType.AUTO):自增</p>
<blockquote>
<p>其他源码解释</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">enum</span> <span class="title">IdType</span> </span>&#123;</span><br><span class="line">    AUTO(<span class="number">0</span>),   <span class="comment">//数据库自增id</span></span><br><span class="line">    NONE(<span class="number">1</span>),    <span class="comment">//未设置主键</span></span><br><span class="line">    INPUT(<span class="number">2</span>),    <span class="comment">//手动输入</span></span><br><span class="line">    ID_WORKER(<span class="number">3</span>),   <span class="comment">//默认得全局唯一id</span></span><br><span class="line">    UUID(<span class="number">4</span>),          <span class="comment">//全局唯一id  uuid</span></span><br><span class="line">    ID_WORKER_STR(<span class="number">5</span>);    <span class="comment">//字符串表示法</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>
<h2 id="自动填充"><a href="#自动填充" class="headerlink" title="自动填充"></a>自动填充</h2><p>创建时间，修改时间！都是自动完成填充.</p>
<p>阿里巴巴开发手册：所有数据库：gmt_create , gmt_modified几乎所有表要具备,而且自动化.</p>
<blockquote>
<h4 id="方式一：数据库级别"><a href="#方式一：数据库级别" class="headerlink" title="方式一：数据库级别"></a>方式一：数据库级别</h4></blockquote>
<p>​    1.在表中新增字段create_time,update_time;配置默认值</p>
<p>​    2.再次新增 </p>
<blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> Date createTime;</span><br><span class="line"><span class="keyword">private</span> Date updateTime;</span><br></pre></td></tr></table></figure>
</blockquote>
<blockquote>
<h4 id="方式二：代码级别"><a href="#方式二：代码级别" class="headerlink" title="方式二：代码级别"></a>方式二：代码级别</h4></blockquote>
<p>​    1.删除数据库默认值</p>
<p>​    2.实体类添加注解</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//字段添加填充内容</span></span><br><span class="line">  <span class="meta">@TableField(fill= FieldFill.INSERT)</span></span><br><span class="line">  <span class="keyword">private</span> Date createTime;</span><br><span class="line"></span><br><span class="line">  <span class="meta">@TableField(fill= FieldFill.INSERT_UPDATE)</span></span><br><span class="line">  <span class="keyword">private</span> Date updateTime;</span><br></pre></td></tr></table></figure>

<p>​    3.编写处理器来处理这个注解</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyMetaObjectHandler</span> <span class="keyword">implements</span> <span class="title">MetaObjectHandler</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 新增填充策略</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> metaObject</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">insertFill</span><span class="params">(MetaObject metaObject)</span> </span>&#123;</span><br><span class="line">        log.info(<span class="string">&quot;start insert fill......&quot;</span>);</span><br><span class="line">        <span class="comment">//设置字段值</span></span><br><span class="line">        <span class="comment">//setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject)</span></span><br><span class="line">        <span class="keyword">this</span>.setFieldValByName(<span class="string">&quot;createTime&quot;</span>,<span class="keyword">new</span> Date(),metaObject);</span><br><span class="line">        <span class="keyword">this</span>.setFieldValByName(<span class="string">&quot;updateTime&quot;</span>,<span class="keyword">new</span> Date(),metaObject);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 更新填充策略</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> metaObject</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">updateFill</span><span class="params">(MetaObject metaObject)</span> </span>&#123;</span><br><span class="line">        log.info(<span class="string">&quot;start update fill......&quot;</span>);</span><br><span class="line">        <span class="keyword">this</span>.setFieldValByName(<span class="string">&quot;updateTime&quot;</span>,<span class="keyword">new</span> Date(),metaObject);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="乐观锁"><a href="#乐观锁" class="headerlink" title="乐观锁"></a>乐观锁</h2><p>其实是一种概念。</p>
<blockquote>
<p>乐观锁：认为不会出现问题，无论做什么都不上锁，如果出了问题，再上锁去操作；比如一个心很大得人</p>
<p>悲观锁：认为做什么都会出现问题，无论干什么都会上锁，再去操作；比如一个很谨慎的人</p>
</blockquote>
<p>乐观锁机制!</p>
<h5 id="实现方式"><a href="#实现方式" class="headerlink" title="实现方式"></a>实现方式</h5><ul>
<li><p>取出记录时，获取当前version</p>
</li>
<li><p>更新时，带上这个version</p>
</li>
<li><p>执行更新时， set version = newVersion where version = oldVersion</p>
</li>
<li><p>如果version不对，就更新失败</p>
</li>
</ul>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">乐观锁：<span class="number">1.</span>先查询，获取版本号 version<span class="operator">=</span><span class="number">1</span></span><br><span class="line">A线程 </span><br><span class="line">update <span class="keyword">user</span> <span class="keyword">set</span>  name<span class="operator">=</span>&quot;122&quot;, version<span class="operator">=</span>version<span class="operator">+</span><span class="number">1</span> <span class="keyword">where</span>  id<span class="operator">=</span><span class="number">2</span> <span class="keyword">and</span> version<span class="operator">=</span><span class="number">1</span></span><br><span class="line"></span><br><span class="line">   B线程   线程抢先完成，这个时候version<span class="operator">=</span><span class="number">2</span>，会导致B修改不成功<span class="operator">!</span></span><br><span class="line">update <span class="keyword">user</span> <span class="keyword">set</span>  name<span class="operator">=</span>&quot;122&quot;, version<span class="operator">=</span>version<span class="operator">+</span><span class="number">1</span> <span class="keyword">where</span>  id<span class="operator">=</span><span class="number">2</span> <span class="keyword">and</span> version<span class="operator">=</span><span class="number">1</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>测试MP的乐观锁插件</p>
</blockquote>
<p>1.数据库添加version</p>
<p>2.实体类添加字段及注解</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Version</span>  <span class="comment">//乐观锁version注解</span></span><br><span class="line"><span class="keyword">private</span> Integer version;</span><br></pre></td></tr></table></figure>

<p>3.添加乐观锁插件</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@MapperScan(&quot;com.my.mybatis_plus.mapper&quot;)</span></span><br><span class="line"><span class="meta">@EnableTransactionManagement</span>  <span class="comment">// 启注解事务管理，等同于xml配置方式的 &lt;tx:annotation-driven /&gt;</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyBatisPlusConfig</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//注册乐观锁插件</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> OptimisticLockerInterceptor <span class="title">optimisticLockerInterceptor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> OptimisticLockerInterceptor();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>4.测试</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//测试乐观锁成功</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testOptimisticLocker</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="comment">//1.查询用户信息</span></span><br><span class="line">    User user=userMapper.selectById(<span class="number">1L</span>);</span><br><span class="line">    <span class="comment">//2.修改用户信息</span></span><br><span class="line">    user.setName(<span class="string">&quot;虾仁&quot;</span>);</span><br><span class="line">    user.setEmail(<span class="string">&quot;虾仁.com&quot;</span>);</span><br><span class="line">    <span class="comment">//3.执行更新操作</span></span><br><span class="line">    userMapper.updateById(user);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//测试乐观锁失败</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testOptimisticLocker2</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="comment">//线程1</span></span><br><span class="line">    User user=userMapper.selectById(<span class="number">1L</span>);</span><br><span class="line">    user.setName(<span class="string">&quot;虾仁一号&quot;</span>);</span><br><span class="line">    user.setEmail(<span class="string">&quot;324234.com&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//线程2 执行插队操作</span></span><br><span class="line">    User user2=userMapper.selectById(<span class="number">1L</span>);</span><br><span class="line">    user2.setName(<span class="string">&quot;虾仁二号&quot;</span>);</span><br><span class="line">    user2.setEmail(<span class="string">&quot;324234.com&quot;</span>);</span><br><span class="line">    userMapper.updateById(user2);</span><br><span class="line">    <span class="comment">//如果没有乐观锁就会覆盖插队线程的值！</span></span><br><span class="line">    <span class="comment">//可以使用自旋锁多次尝试提交</span></span><br><span class="line">    userMapper.updateById(user);</span><br><span class="line">&#125;</span><br><span class="line">  </span><br></pre></td></tr></table></figure>

<blockquote>
<p>version:作为乐观锁的一种条件限制；</p>
</blockquote>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">如上乐观锁失败执行的<span class="keyword">sql</span>日志：</span><br><span class="line">        <span class="number">1.</span><span class="keyword">user</span>查询</span><br><span class="line">        	<span class="keyword">SELECT</span> id,name,age,email,version,create_time,update_time <span class="keyword">FROM</span> <span class="keyword">user</span> <span class="keyword">WHERE</span> id<span class="operator">=</span>? </span><br><span class="line">			<span class="operator">=</span><span class="operator">=</span><span class="operator">&gt;</span> Parameters: <span class="number">1</span>(Long)</span><br><span class="line">			<span class="operator">&lt;=</span><span class="operator">=</span>    Columns: id, name, age, email, version, create_time, update_time</span><br><span class="line">			<span class="operator">&lt;=</span><span class="operator">=</span>        <span class="type">Row</span>: <span class="number">1</span>, 虾仁, <span class="number">18</span>, 虾仁.com, <span class="number">2</span>, <span class="keyword">null</span>, <span class="number">2022</span><span class="number">-02</span><span class="number">-22</span> <span class="number">14</span>:<span class="number">04</span>:<span class="number">37</span></span><br><span class="line">			<span class="operator">&lt;=</span><span class="operator">=</span>      Total: <span class="number">1</span></span><br><span class="line">        <span class="number">2.</span>user2查询</span><br><span class="line">            <span class="keyword">SELECT</span> id,name,age,email,version,create_time,update_time <span class="keyword">FROM</span> <span class="keyword">user</span> <span class="keyword">WHERE</span> id<span class="operator">=</span>? </span><br><span class="line">			<span class="operator">=</span><span class="operator">=</span><span class="operator">&gt;</span> Parameters: <span class="number">1</span>(Long)</span><br><span class="line">			<span class="operator">&lt;=</span><span class="operator">=</span>    Columns: id, name, age, email, version, create_time, update_time</span><br><span class="line">			<span class="operator">&lt;=</span><span class="operator">=</span>        <span class="type">Row</span>: <span class="number">1</span>, 虾仁, <span class="number">18</span>, 虾仁.com, <span class="number">2</span>, <span class="keyword">null</span>, <span class="number">2022</span><span class="number">-02</span><span class="number">-22</span> <span class="number">14</span>:<span class="number">04</span>:<span class="number">37</span></span><br><span class="line">			<span class="operator">&lt;=</span><span class="operator">=</span>      Total: <span class="number">1</span></span><br><span class="line">        <span class="number">3.</span>user2修改</span><br><span class="line">            UPDATE <span class="keyword">user</span> <span class="keyword">SET</span> name<span class="operator">=</span>?, age<span class="operator">=</span>?, email<span class="operator">=</span>?, version<span class="operator">=</span>?, update_time<span class="operator">=</span>? <span class="keyword">WHERE</span> id<span class="operator">=</span>? <span class="keyword">AND</span> version<span class="operator">=</span>? </span><br><span class="line">			<span class="operator">=</span><span class="operator">=</span><span class="operator">&gt;</span> Parameters: 虾仁二号(String), <span class="number">18</span>(<span class="type">Integer</span>), <span class="number">324234.</span>com(String), <span class="number">3</span>(<span class="type">Integer</span>), <span class="number">2022</span><span class="number">-02</span><span class="number">-22</span> 					<span class="number">14</span>:<span class="number">07</span>:<span class="number">04.081</span>(<span class="type">Timestamp</span>), <span class="number">1</span>(Long), <span class="number">2</span>(<span class="type">Integer</span>)</span><br><span class="line">			<span class="operator">&lt;=</span><span class="operator">=</span>    Updates: <span class="number">1</span></span><br><span class="line">        <span class="number">4.</span><span class="keyword">user</span>修改(因为version已修改为<span class="number">3</span>，导致<span class="keyword">user</span>修改失败;如没有此version乐观锁限制,这一步将会覆盖上一步修改)   </span><br><span class="line">            UPDATE <span class="keyword">user</span> <span class="keyword">SET</span> name<span class="operator">=</span>?, age<span class="operator">=</span>?, email<span class="operator">=</span>?, version<span class="operator">=</span>?, update_time<span class="operator">=</span>? <span class="keyword">WHERE</span> id<span class="operator">=</span>? <span class="keyword">AND</span> version<span class="operator">=</span>? </span><br><span class="line">			<span class="operator">=</span><span class="operator">=</span><span class="operator">&gt;</span> Parameters: 虾仁一号(String), <span class="number">18</span>(<span class="type">Integer</span>), <span class="number">324234.</span>com(String), <span class="number">3</span>(<span class="type">Integer</span>), <span class="number">2022</span><span class="number">-02</span><span class="number">-22</span> 					<span class="number">14</span>:<span class="number">07</span>:<span class="number">04.089</span>(<span class="type">Timestamp</span>), <span class="number">1</span>(Long), <span class="number">2</span>(<span class="type">Integer</span>)</span><br><span class="line">			<span class="operator">&lt;=</span><span class="operator">=</span>    Updates: <span class="number">0</span>   </span><br></pre></td></tr></table></figure>

<h2 id="查询操作"><a href="#查询操作" class="headerlink" title="查询操作"></a>查询操作</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//测试查询</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testSelectById</span><span class="params">()</span></span>&#123;</span><br><span class="line">    User user=userMapper.selectById(<span class="number">1L</span>);</span><br><span class="line">    System.out.println(user);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//批量查询</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testSelectBatchIds</span><span class="params">()</span></span>&#123;</span><br><span class="line">    List&lt;User&gt; user=userMapper.selectBatchIds(Arrays.asList(<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>));</span><br><span class="line">    user.forEach(System.out::println);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//条件查询map</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testSelectByMap</span><span class="params">()</span></span>&#123;</span><br><span class="line">    HashMap&lt;String, Object&gt; stringObjectHashMap = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">    <span class="comment">//自定义查询</span></span><br><span class="line">    stringObjectHashMap.put(<span class="string">&quot;name&quot;</span>,<span class="string">&quot;虾仁二号&quot;</span>);</span><br><span class="line">    List&lt;User&gt; user=userMapper.selectByMap(stringObjectHashMap);</span><br><span class="line">    user.forEach(System.out::println);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="分页查询"><a href="#分页查询" class="headerlink" title="分页查询"></a>分页查询</h2><p>1.原始的limit进行分页</p>
<p>2.pageHelpere第三方插件</p>
<p>3.MP其实内置了分页插件</p>
<blockquote>
<p>如何使用</p>
</blockquote>
<p>1.配置分页拦截器主键</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@MapperScan(&quot;com.my.mybatis_plus.mapper&quot;)</span></span><br><span class="line"><span class="meta">@EnableTransactionManagement</span> <span class="comment">// 启注解事务管理，等同于xml配置方式的 &lt;tx:annotation-driven /&gt;</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyBatisPlusConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//注册乐观锁插件</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> OptimisticLockerInterceptor <span class="title">optimisticLockerInterceptor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> OptimisticLockerInterceptor();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//分页注册</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> PaginationInterceptor <span class="title">paginationInterceptor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> PaginationInterceptor();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>2.直接使用Page对象</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//测试分页查询</span></span><br><span class="line">  <span class="meta">@Test</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testPage</span><span class="params">()</span></span>&#123;</span><br><span class="line">      Page&lt;User&gt; page=<span class="keyword">new</span> Page&lt;&gt;(<span class="number">1</span>,<span class="number">5</span>);</span><br><span class="line">      userMapper.selectPage(page,<span class="keyword">null</span>);</span><br><span class="line">      page.getRecords().forEach(System.out::print);</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<h2 id="删除操作"><a href="#删除操作" class="headerlink" title="删除操作"></a>删除操作</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//批量删除</span></span><br><span class="line"> <span class="meta">@Test</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testDeleteBatchId</span><span class="params">()</span></span>&#123;</span><br><span class="line">     <span class="keyword">int</span> result=userMapper.deleteBatchIds(Arrays.asList(<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>));</span><br><span class="line">     System.out.println(result);</span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line"> <span class="comment">//通过map删除</span></span><br><span class="line"> <span class="meta">@Test</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testDeleteMap</span><span class="params">()</span></span>&#123;</span><br><span class="line">     HashMap&lt;String, Object&gt; stringObjectHashMap = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">     stringObjectHashMap.put(<span class="string">&quot;id&quot;</span>,<span class="string">&quot;1&quot;</span>);</span><br><span class="line">     <span class="keyword">int</span> result=userMapper.deleteByMap(stringObjectHashMap);</span><br><span class="line">     System.out.println(result);</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>

<h2 id="逻辑删除"><a href="#逻辑删除" class="headerlink" title="逻辑删除"></a>逻辑删除</h2><blockquote>
<p>物理删除：从数据库中直接移除</p>
<p>逻辑删除：在数据库中没有被移除，而是通过一个变量让他失效! deleted=0=&gt;deleted=1</p>
</blockquote>
<p>1.表中添加deleted字段</p>
<p>2.实体类添加字段</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@TableLogic</span>  <span class="comment">//逻辑删除</span></span><br><span class="line"><span class="keyword">private</span> Integer deleted;</span><br></pre></td></tr></table></figure>

<p>3.配置</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//逻辑删除配置</span></span><br><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> ISqlInjector <span class="title">sqlInjector</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> LogicSqlInjector();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#逻辑删除配置</span></span><br><span class="line"><span class="string">mybatis-plus.global-config.db-config.logic-delete-value=1</span>  <span class="comment"># 逻辑已删除值(默认为 1)</span></span><br><span class="line"><span class="string">mybatis-plus.global-config.db-config.logic-not-delete-value=0</span>  <span class="comment"># 逻辑未删除值(默认为 0)</span></span><br></pre></td></tr></table></figure>

<p>说明:</p>
<p>只对自动注入的sql起效:</p>
<ul>
<li>插入: 不作限制</li>
<li>查找: 追加where条件过滤掉已删除数据,且使用 wrapper.entity 生成的where条件会忽略该字段</li>
<li>更新: 追加where条件防止更新到已删除数据,且使用 wrapper.entity 生成的where条件会忽略该字段</li>
<li>删除: 转变为 更新</li>
</ul>
<p>例如:</p>
<ul>
<li>删除: <code>update user set deleted=1 where id = 1 and deleted=0</code></li>
<li>查找: <code>select id,name,deleted from user where deleted=0</code></li>
</ul>
<h2 id="SQL性能分析打印插件"><a href="#SQL性能分析打印插件" class="headerlink" title="SQL性能分析打印插件"></a>SQL性能分析打印插件</h2><blockquote>
<h4 id="旧版"><a href="#旧版" class="headerlink" title="旧版"></a>旧版</h4></blockquote>
<p>1.导入插件</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * sql执行效率插件</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="meta">@Profile(&#123;&quot;dev&quot;,&quot;test&quot;&#125;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> PerformanceInterceptor <span class="title">performanceInterceptor</span><span class="params">()</span></span>&#123;</span><br><span class="line">    PerformanceInterceptor performanceInterceptor = <span class="keyword">new</span> PerformanceInterceptor();</span><br><span class="line">    <span class="comment">// ms 设置sql最大执行时间,超过不执行</span></span><br><span class="line">    performanceInterceptor.setMaxTime(<span class="number">100</span>);</span><br><span class="line">    <span class="comment">//sql格式化</span></span><br><span class="line">    performanceInterceptor.setFormat(<span class="keyword">true</span>);</span><br><span class="line">    <span class="keyword">return</span> performanceInterceptor;</span><br><span class="line">&#125;</span><br><span class="line">	</span><br></pre></td></tr></table></figure>

<p>最好只在SpringBoot中配置环境为dev或者test使用！提高开发效率</p>
<blockquote>
<h4 id="新版"><a href="#新版" class="headerlink" title="新版"></a>新版</h4></blockquote>
<p><strong>1.添加依赖</strong></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--        sql打印分析--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>p6spy<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>p6spy<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.9.1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><strong>2.application.yml配置</strong></p>
<p>​     数据库配置修改:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">#修改前</span><br><span class="line">spring:</span><br><span class="line">  datasource:</span><br><span class="line">    driver-class-name: com.mysql.cj.jdbc.Driver</span><br><span class="line">    username: root</span><br><span class="line">    password: root</span><br><span class="line">    url: jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&amp;useUnicode=tru&amp;characterEncoding=utf-            		8&amp;serverTimezone=GMT%2B8&amp;allowMultiQueries=true</span><br><span class="line"></span><br><span class="line">#修改后：</span><br><span class="line">spring:</span><br><span class="line">  datasource:</span><br><span class="line">    driver-class-name: com.p6spy.engine.spy.P6SpyDriver</span><br><span class="line">    username: root</span><br><span class="line">    password: root</span><br><span class="line">    url: jdbc:p6spy:mysql://localhost:3306/mybatis_plus?useSSL=false&amp;useUnicode=tru&amp;characterEncoding=utf-            8&amp;serverTimezone=GMT%2B8&amp;allowMultiQueries=true</span><br></pre></td></tr></table></figure>

<p>3.创建spy.properties文件</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">#3.2.1以上使用</span><br><span class="line">modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory</span><br><span class="line">#3.2.1以下使用或者不配置</span><br><span class="line">#modulelist=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory</span><br><span class="line"># 自定义日志打印</span><br><span class="line">logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger</span><br><span class="line">#日志输出到控制台</span><br><span class="line">appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger</span><br><span class="line"># 使用日志系统记录 sql</span><br><span class="line">#appender=com.p6spy.engine.spy.appender.Slf4JLogger</span><br><span class="line"># 设置 p6spy driver 代理</span><br><span class="line">deregisterdrivers=true</span><br><span class="line"># 取消JDBC URL前缀</span><br><span class="line">useprefix=true</span><br><span class="line"># 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.</span><br><span class="line">excludecategories=info,debug,result,commit,resultset</span><br><span class="line"># 日期格式</span><br><span class="line">dateformat=yyyy-MM-dd HH:mm:ss</span><br><span class="line"># 实际驱动可多个</span><br><span class="line">#driverlist=org.h2.Driver</span><br><span class="line"># 是否开启慢SQL记录</span><br><span class="line">outagedetection=true</span><br><span class="line"># 慢SQL记录标准 2 秒</span><br><span class="line">outagedetectioninterval=2</span><br></pre></td></tr></table></figure>





<h2 id="条件查询Wrapper"><a href="#条件查询Wrapper" class="headerlink" title="条件查询Wrapper"></a>条件查询Wrapper</h2><p>用来写一些复杂的sql</p>
<p>1.测试一</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//查询name不为空，email不为空，age大于等于20</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">selecteWrapper</span><span class="params">()</span></span>&#123;</span><br><span class="line">    QueryWrapper&lt;User&gt; wrapper=<span class="keyword">new</span> QueryWrapper&lt;&gt;();</span><br><span class="line">    wrapper.isNotNull(<span class="string">&quot;name&quot;</span>)    <span class="comment">//is not null</span></span><br><span class="line">            .isNotNull(<span class="string">&quot;email&quot;</span>)  <span class="comment">//is not null</span></span><br><span class="line">            .ge(<span class="string">&quot;age&quot;</span>,<span class="number">20</span>);       <span class="comment">//&gt;=</span></span><br><span class="line">    userMapper.selectList(wrapper).forEach(System.out::println);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>2.测试二</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line">  <span class="function"><span class="keyword">void</span> <span class="title">test2</span><span class="params">()</span></span>&#123;</span><br><span class="line">          <span class="comment">//查询name</span></span><br><span class="line">      QueryWrapper&lt;User&gt; userQueryWrapper = <span class="keyword">new</span> QueryWrapper&lt;&gt;();</span><br><span class="line">      userQueryWrapper.eq(<span class="string">&quot;name&quot;</span>,<span class="string">&quot;pzy&quot;</span>);</span><br><span class="line">      User user = userMapper.selectOne(userQueryWrapper);</span><br><span class="line">      System.out.println(user);</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<p>3.测试三</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"> <span class="function"><span class="keyword">void</span> <span class="title">test3</span><span class="params">()</span></span>&#123;</span><br><span class="line">     <span class="comment">//查询年龄20到30之间</span></span><br><span class="line">     QueryWrapper&lt;User&gt; userQueryWrapper = <span class="keyword">new</span> QueryWrapper&lt;&gt;();</span><br><span class="line">     userQueryWrapper.between(<span class="string">&quot;age&quot;</span>,<span class="number">10</span>,<span class="number">30</span>);</span><br><span class="line">     Integer count=userMapper.selectCount(userQueryWrapper);</span><br><span class="line">     System.out.println(count);</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>

<p>4.测试四</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">test4</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="comment">//模糊查询</span></span><br><span class="line">    QueryWrapper&lt;User&gt; userQueryWrapper = <span class="keyword">new</span> QueryWrapper&lt;&gt;();</span><br><span class="line">    userQueryWrapper.notLike(<span class="string">&quot;name&quot;</span>,<span class="string">&quot;e&quot;</span>).likeLeft(<span class="string">&quot;email&quot;</span>,<span class="string">&quot;1&quot;</span>);</span><br><span class="line">    userMapper.selectMaps(userQueryWrapper).forEach(System.out::println);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>5.测试五</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"> <span class="function"><span class="keyword">void</span> <span class="title">test5</span><span class="params">()</span></span>&#123;</span><br><span class="line">     <span class="comment">//子查询</span></span><br><span class="line">     QueryWrapper&lt;User&gt; userQueryWrapper = <span class="keyword">new</span> QueryWrapper&lt;&gt;();</span><br><span class="line">     userQueryWrapper.inSql(<span class="string">&quot;id&quot;</span>,<span class="string">&quot;select id from user where id&gt;2&quot;</span>);</span><br><span class="line">     userMapper.selectObjs(userQueryWrapper).forEach(System.out::println);</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>



<h2 id="代码生成器"><a href="#代码生成器" class="headerlink" title="代码生成器"></a>代码生成器</h2><p>AutoGenerator 是 MyBatis-Plus 的代码生成器，通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码，极大的提升了开发效率。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.my.mybatis_plus;</span><br><span class="line"><span class="keyword">import</span> com.baomidou.mybatisplus.annotation.DbType;</span><br><span class="line"><span class="keyword">import</span> com.baomidou.mybatisplus.annotation.FieldFill;</span><br><span class="line"><span class="keyword">import</span> com.baomidou.mybatisplus.annotation.IdType;</span><br><span class="line"><span class="keyword">import</span> com.baomidou.mybatisplus.generator.AutoGenerator;</span><br><span class="line"><span class="keyword">import</span> com.baomidou.mybatisplus.generator.config.DataSourceConfig;</span><br><span class="line"><span class="keyword">import</span> com.baomidou.mybatisplus.generator.config.GlobalConfig;</span><br><span class="line"><span class="keyword">import</span> com.baomidou.mybatisplus.generator.config.PackageConfig;</span><br><span class="line"><span class="keyword">import</span> com.baomidou.mybatisplus.generator.config.StrategyConfig;</span><br><span class="line"><span class="keyword">import</span> com.baomidou.mybatisplus.generator.config.po.TableFill;</span><br><span class="line"><span class="keyword">import</span> com.baomidou.mybatisplus.generator.config.rules.DateType;</span><br><span class="line"><span class="keyword">import</span> com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;</span><br><span class="line"><span class="keyword">import</span> java.util.ArrayList;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> pzy</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@version</span> 1.0</span></span><br><span class="line"><span class="comment"> * 代码自动生成器</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CodeOpen</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//需要构建一个代码自动生成器对象</span></span><br><span class="line">        AutoGenerator auto = <span class="keyword">new</span> AutoGenerator();</span><br><span class="line">        <span class="comment">//全局配置</span></span><br><span class="line">        GlobalConfig gc = <span class="keyword">new</span> GlobalConfig();</span><br><span class="line">        String property = System.getProperty(<span class="string">&quot;user.dir&quot;</span>);   <span class="comment">//获取项目路径</span></span><br><span class="line">        gc.setOutputDir(property + <span class="string">&quot;/src/main/java&quot;</span>);</span><br><span class="line">        gc.setFileOverride(<span class="keyword">false</span>);  <span class="comment">//是否覆盖</span></span><br><span class="line">        gc.setServiceName(<span class="string">&quot;%sService&quot;</span>);  <span class="comment">//去Service的I前缀</span></span><br><span class="line">        gc.setIdType(IdType.ID_WORKER);   <span class="comment">//主键生成方式</span></span><br><span class="line">        gc.setDateType(DateType.ONLY_DATE);</span><br><span class="line">        gc.setSwagger2(<span class="keyword">true</span>);</span><br><span class="line">        gc.setAuthor(<span class="string">&quot;pzy&quot;</span>);  <span class="comment">//标记作者名称</span></span><br><span class="line">        gc.setOpen(<span class="keyword">false</span>); <span class="comment">//是否打开资源管理器</span></span><br><span class="line">        auto.setGlobalConfig(gc);</span><br><span class="line">        <span class="comment">//数据源配置</span></span><br><span class="line">        DataSourceConfig dc=<span class="keyword">new</span> DataSourceConfig();</span><br><span class="line">        dc.setUrl(<span class="string">&quot;jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&amp;useUnicode=tru&amp;characterEncoding=utf-8&amp;serverTimezone=GMT%2B8&amp;allowMultiQueries=true&quot;</span>);</span><br><span class="line">        <span class="comment">//dc.setSchemaName(&quot;mybatis_plus&quot;);</span></span><br><span class="line">        dc.setDriverName(<span class="string">&quot;com.mysql.cj.jdbc.Driver&quot;</span>);</span><br><span class="line">        dc.setUsername(<span class="string">&quot;root&quot;</span>);</span><br><span class="line">        dc.setPassword(<span class="string">&quot;root&quot;</span>);</span><br><span class="line">        dc.setDbType(DbType.MYSQL);</span><br><span class="line">        auto.setDataSource(dc);</span><br><span class="line">        <span class="comment">//包配置</span></span><br><span class="line">        PackageConfig pc = <span class="keyword">new</span> PackageConfig();</span><br><span class="line">        pc.setModuleName(<span class="string">&quot;moudle&quot;</span>);     <span class="comment">//父类包名</span></span><br><span class="line">        pc.setParent(<span class="string">&quot;com.my.mybatis_plus&quot;</span>);  <span class="comment">//包路径</span></span><br><span class="line">        pc.setEntity(<span class="string">&quot;entity&quot;</span>);</span><br><span class="line">        pc.setMapper(<span class="string">&quot;mapper&quot;</span>);</span><br><span class="line">        pc.setService(<span class="string">&quot;service&quot;</span>);</span><br><span class="line">        pc.setController(<span class="string">&quot;controller&quot;</span>);</span><br><span class="line">        auto.setPackageInfo(pc);</span><br><span class="line">        <span class="comment">//策略配置</span></span><br><span class="line">        StrategyConfig strategy = <span class="keyword">new</span> StrategyConfig();</span><br><span class="line">        strategy.setInclude(<span class="string">&quot;user&quot;</span>);   <span class="comment">//设置要映射的表,可以多个</span></span><br><span class="line">        strategy.setNaming(NamingStrategy.underline_to_camel);  <span class="comment">//表名下划线转驼峰</span></span><br><span class="line">        strategy.setColumnNaming(NamingStrategy.underline_to_camel);   <span class="comment">//列下划线转驼峰</span></span><br><span class="line">        strategy.setEntityLombokModel(<span class="keyword">true</span>);   <span class="comment">//自动lombok</span></span><br><span class="line">        strategy.setLogicDeleteFieldName(<span class="string">&quot;deleted&quot;</span>); <span class="comment">//配置逻辑删除字段</span></span><br><span class="line">        <span class="comment">//自动填充策略</span></span><br><span class="line">        ArrayList&lt;TableFill&gt; tableFills = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        TableFill createTime = <span class="keyword">new</span> TableFill(<span class="string">&quot;create_time&quot;</span>, FieldFill.INSERT);</span><br><span class="line">        TableFill updateTime = <span class="keyword">new</span> TableFill(<span class="string">&quot;update_time&quot;</span>, FieldFill.INSERT_UPDATE);</span><br><span class="line">        tableFills.add(createTime);</span><br><span class="line">        tableFills.add(updateTime);</span><br><span class="line">        strategy.setTableFillList(tableFills);</span><br><span class="line">        <span class="comment">//乐观锁</span></span><br><span class="line">        strategy.setVersionFieldName(<span class="string">&quot;version&quot;</span>);   <span class="comment">//乐观锁字段</span></span><br><span class="line">        strategy.setRestControllerStyle(<span class="keyword">true</span>);  <span class="comment">//localhost:8080/hello_id_2</span></span><br><span class="line">        auto.setStrategy(strategy);</span><br><span class="line">        <span class="comment">//执行生成</span></span><br><span class="line">        auto.execute();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>







<p>写于日期：2022-2-22 16:41</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined" rel="external nofollow noreferrer">IU的小迷弟</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://www.loveiu.top/20220622/mybatiis_plus/">https://www.loveiu.top/20220622/mybatiis_plus/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow noreferrer" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://www.loveiu.top" target="_blank">IU的小迷弟</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E7%AC%94%E8%AE%B0/">-笔记</a></div><div class="post_share"><div class="social-share" data-image="/img/79.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://unpkg.com/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://unpkg.com/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/img/weicat.png" target="_blank"><img class="post-qr-code-img" data-lazy-src="/img/weicat.png" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/img/zfb.jpg" target="_blank"><img class="post-qr-code-img" data-lazy-src="/img/zfb.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/20220622/git/"><img class="prev-cover" data-lazy-src="/img/35.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Git命令合集</div></div></a></div><div class="next-post pull-right"><a href="/20220517/Mongod-Server-install/"><img class="next-cover" data-lazy-src="/img/80.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Mongodb服务教程</div></div></a></div></nav><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Mybatis-Plus"><span class="toc-number">1.</span> <span class="toc-text">Mybatis-Plus</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B"><span class="toc-number">2.</span> <span class="toc-text">快速开始</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E9%85%8D%E7%BD%AE%E6%97%A5%E5%BF%97"><span class="toc-number">3.</span> <span class="toc-text">配置日志</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#CRUD%E6%89%A9%E5%B1%95"><span class="toc-number">4.</span> <span class="toc-text">CRUD扩展</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#CRUD%E6%B5%8B%E8%AF%95"><span class="toc-number">4.1.</span> <span class="toc-text">CRUD测试</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%BB%E9%94%AE%E7%94%9F%E6%88%90%E7%AD%96%E7%95%A5"><span class="toc-number">4.2.</span> <span class="toc-text">主键生成策略</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%87%AA%E5%8A%A8%E5%A1%AB%E5%85%85"><span class="toc-number">4.3.</span> <span class="toc-text">自动填充</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%B9%E5%BC%8F%E4%B8%80%EF%BC%9A%E6%95%B0%E6%8D%AE%E5%BA%93%E7%BA%A7%E5%88%AB"><span class="toc-number">4.3.0.1.</span> <span class="toc-text">方式一：数据库级别</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%B9%E5%BC%8F%E4%BA%8C%EF%BC%9A%E4%BB%A3%E7%A0%81%E7%BA%A7%E5%88%AB"><span class="toc-number">4.3.0.2.</span> <span class="toc-text">方式二：代码级别</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B9%90%E8%A7%82%E9%94%81"><span class="toc-number">4.4.</span> <span class="toc-text">乐观锁</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%AE%9E%E7%8E%B0%E6%96%B9%E5%BC%8F"><span class="toc-number">4.4.0.0.1.</span> <span class="toc-text">实现方式</span></a></li></ol></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%9F%A5%E8%AF%A2%E6%93%8D%E4%BD%9C"><span class="toc-number">4.5.</span> <span class="toc-text">查询操作</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%86%E9%A1%B5%E6%9F%A5%E8%AF%A2"><span class="toc-number">4.6.</span> <span class="toc-text">分页查询</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%A0%E9%99%A4%E6%93%8D%E4%BD%9C"><span class="toc-number">4.7.</span> <span class="toc-text">删除操作</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%80%BB%E8%BE%91%E5%88%A0%E9%99%A4"><span class="toc-number">4.8.</span> <span class="toc-text">逻辑删除</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#SQL%E6%80%A7%E8%83%BD%E5%88%86%E6%9E%90%E6%89%93%E5%8D%B0%E6%8F%92%E4%BB%B6"><span class="toc-number">4.9.</span> <span class="toc-text">SQL性能分析打印插件</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%97%A7%E7%89%88"><span class="toc-number">4.9.0.1.</span> <span class="toc-text">旧版</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%B0%E7%89%88"><span class="toc-number">4.9.0.2.</span> <span class="toc-text">新版</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%9D%A1%E4%BB%B6%E6%9F%A5%E8%AF%A2Wrapper"><span class="toc-number">4.10.</span> <span class="toc-text">条件查询Wrapper</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E7%94%9F%E6%88%90%E5%99%A8"><span class="toc-number">4.11.</span> <span class="toc-text">代码生成器</span></a></li></ol></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2021 - 2022 By IU的小迷弟</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener external nofollow noreferrer" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener external nofollow noreferrer" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a href="/">我见青山多妩媚，料青山见我应如是</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="translateLink" type="button" title="简繁转换">簡</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="rightside.chat_btn"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://instant.page/5.1.0" type="module"></script><script src="https://unpkg.com/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.bootcdn.net/ajax/libs/node-snackbar/0.1.9/snackbar.min.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://unpkg.com/pangu/dist/browser/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (true){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.bootcdn.net/ajax/libs/mermaid/9.1.1/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      true && mermaid.init()
    })
  }
}</script><script>(()=>{
  const $countDom = document.getElementById('twikoo-count')
  const init = () => {
    twikoo.init(Object.assign({
      el: '#twikoo-wrap',
      envId: 'https://twikoo-git-dev-pzloveyou.vercel.app/',
      //region: ''
      // region: 'ap-guangzhou', // 环境地域，默认为 ap-shanghai，腾讯云环境填 ap-shanghai 或 ap-guangzhou；Vercel 环境不填
        // path: location.pathname, // 用于区分不同文章的自定义 js 路径，如果您的文章路径不是 location.pathname，需传此参数
        // lang: 'zh-CN', // 用于手动设定评论区语言，支持的语言列表 https://github.com/imaegoo/twikoo/blob/main/src/js/utils/i18n/index.js
    }, null))
  }

  const getCount = () => {
    twikoo.getCommentsCount({
      envId: 'https://twikoo-git-dev-pzloveyou.vercel.app/',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(function (res) {
      $countDom.innerText = res[0].count
    }).catch(function (err) {
      console.error(err);
    });
  }

  const loadTwikoo = (bool = false) => {
    if (typeof twikoo === 'object') {
      init()
      bool && $countDom && setTimeout(getCount,0)
    } else {
      getScript('https://cdn.staticfile.org/twikoo/1.5.10/twikoo.all.min.js').then(()=> {
        init()
        bool && $countDom && setTimeout(getCount,0)
      })
    }
  }

  if ('Twikoo' === 'Twikoo' || !true) {
    if (true) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo(true)
  } else {
    window.loadOtherComment = () => {
      loadTwikoo()
    }
  }
})()</script></div><script>window.addEventListener('load', () => {
  const changeContent = (content) => {
    if (content === '') return content

    content = content.replace(/<img.*?src="(.*?)"?[^\>]+>/ig, '[图片]') // replace image link
    content = content.replace(/<a[^>]+?href=["']?([^"']+)["']?[^>]*>([^<]+)<\/a>/gi, '[链接]') // replace url
    content = content.replace(/<pre><code>.*?<\/pre>/gi, '[代码]') // replace code
    content = content.replace(/<[^>]+>/g,"") // remove html tag

    if (content.length > 150) {
      content = content.substring(0,150) + '...'
    }
    return content
  }

  const getComment = () => {
    const runTwikoo = () => {
      twikoo.getRecentComments({
        envId: 'https://twikoo-git-dev-pzloveyou.vercel.app/',
        region: '',
        pageSize: 6,
        includeReply: true
      }).then(function (res) {
        const twikooArray = res.map(e => {
          return {
            'content': changeContent(e.comment),
            'avatar': e.avatar,
            'nick': e.nick,
            'url': e.url + '#' + e.id,
            'date': new Date(e.created).toISOString()
          }
        })

        saveToLocal.set('twikoo-newest-comments', JSON.stringify(twikooArray), 10/(60*24))
        generateHtml(twikooArray)
      }).catch(function (err) {
        const $dom = document.querySelector('#card-newest-comments .aside-list')
        $dom.innerHTML= "无法获取评论，请确认相关配置是否正确"
      })
    }

    if (typeof twikoo === 'object') {
      runTwikoo()
    } else {
      getScript('https://cdn.staticfile.org/twikoo/1.5.10/twikoo.all.min.js').then(runTwikoo)
    }
  }

  const generateHtml = array => {
    let result = ''

    if (array.length) {
      for (let i = 0; i < array.length; i++) {
        result += '<div class=\'aside-list-item\'>'

        if (true) {
          const name = 'data-lazy-src'
          result += `<a href='${array[i].url}' class='thumbnail'><img ${name}='${array[i].avatar}' alt='${array[i].nick}'></a>`
        }
        
        result += `<div class='content'>
        <a class='comment' href='${array[i].url}'>${array[i].content}</a>
        <div class='name'><span>${array[i].nick} / </span><time datetime="${array[i].date}">${btf.diffDate(array[i].date, true)}</time></div>
        </div></div>`
      }
    } else {
      result += '没有评论'
    }

    let $dom = document.querySelector('#card-newest-comments .aside-list')
    $dom.innerHTML= result
    window.lazyLoadInstance && window.lazyLoadInstance.update()
    window.pjax && window.pjax.refresh($dom)
  }

  const newestCommentInit = () => {
    if (document.querySelector('#card-newest-comments .aside-list')) {
      const data = saveToLocal.get('twikoo-newest-comments')
      if (data) {
        generateHtml(JSON.parse(data))
      } else {
        getComment()
      }
    }
  }

  newestCommentInit()
  document.addEventListener('pjax:complete', newestCommentInit)
})</script><style type="text/css">#toggle-sidebar {left:100px}</style><script src="/edit/randomBackground.js"></script><div class="aplayer no-destroy" data-id="2153548870" data-server="netease" data-type="playlist" data-fixed="true" data-mini="true" data-listFolded="false" data-order="random" data-preload="none" data-autoplay="false" muted></div><script id="click-show-text" src="https://unpkg.com/butterfly-extsrc@1/dist/click-show-text.min.js" data-mobile="false" data-text="IU,iu" data-fontsize="15px" data-random="false" async="async"></script><link rel="stylesheet" href="https://unpkg.com/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://unpkg.com/aplayer/dist/APlayer.min.js"></script><script src="https://unpkg.com/meting@1.2.0/dist/Meting.min.js"></script><script src="https://unpkg.com/pjax/pjax.min.js"></script><script>let pjaxSelectors = [
  'title',
  '#config-diff',
  '#body-wrap',
  '#rightside-config-hide',
  '#rightside-config-show',
  '.js-pjax'
]

if (false) {
  pjaxSelectors.unshift('meta[property="og:image"]', 'meta[property="og:title"]', 'meta[property="og:url"]')
}

var pjax = new Pjax({
  elements: 'a:not([target="_blank"]):not([href="/img/"]):not([href="/image/"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // Analytics
  if (false) {
    MtaH5.pgv()
  }

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})


document.addEventListener('pjax:send', function () {
  typeof preloader === 'object' && preloader.initLoading()
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="/js/busuanzi.pure.mini.js"></script></div></body></html>